<template>
  <div class="detail-page">
    <template>
      <div class="detail-page">
        <van-nav-bar
          left-text="返回"
          @click-left="$router.back()"
          fixed
          title="面经详情"
          class="custom-nav-bar"
        />
        <header class="header">
          <h1>{{ detail.stem }}</h1>
          <p>
            {{ detail.createdAt }} | {{ detail.views }} 浏览量 |
            {{ detail.likeCount }} 点赞数
          </p>
          <p>
            <img :src="detail.avatar" alt />
            <span>{{ detail.creator }}</span>
          </p>
        </header>
        <main class="body" v-html="detail.content"></main>
        <div class="opt">
          <van-icon
            :class="{ active: detail.likeFlag }"
            @click="toggleLike()"
            name="like-o"
          />
          <van-icon
            :class="{ active: detail.collectFlag }"
            @click="toggleCollect()"
            name="star-o"
          />
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import { articleDetailApi, articleLikeApi } from '@/api/article'
export default {
  name: 'detail-page',
  data () {
    return {
      detail: {}
    }
  },
  async created () {
    const res = await articleDetailApi(this.$route.query.id)
    console.log(res)
    this.detail = res.data.data
    console.log(this.detail)
  },
  methods: {
    async toggleLike () {
      this.detail.likeFlag = !this.detail.likeFlag
      await articleLikeApi({
        id: this.detail.id,
        optType: 1
      })

      if (this.detail.likeFlag) {
        this.detail.likeCount++
        this.$toast.success('点赞成功')
      } else {
        this.detail.likeCount--
      }
    },
    async toggleCollect () {
      this.detail.collectFlag = !this.detail.collectFlag
      await articleLikeApi({
        id: this.detail.id,
        optType: 2
      })
      if (this.detail.collectFlag) {
        this.detail.collectCount++
        this.$toast.success('收藏成功')
      } else {
        this.detail.collectCount--
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .custom-nav-bar .van-nav-bar__title {
  /* 设置标题文字颜色 */
  color: rgb(129, 137, 250);
  font-weight: 700; /* 设置标题文字大小 */
}
.detail-page {
  margin-top: 20px;
  overflow: hidden;
  padding: 0 15px;
  .header {
    h1 {
      font-size: 24px;
    }
    p {
      color: #999;
      font-size: 12px;
      display: flex;
      align-items: center;
    }
    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      overflow: hidden;
    }
  }
  .opt {
    position: fixed;
    bottom: 100px;
    right: 0;
    > .van-icon {
      margin-right: 20px;
      background: #fff;
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      border-radius: 50%;
      box-shadow: 2px 2px 10px #ccc;
      font-size: 18px;
      &.active {
        background: rgb(25, 137, 250);
        color: #fff;
      }
    }
  }
}
</style>
